/**
 * Created by John on 2015-04-23.
 */
var mysql = require('mysql');
var DB_NAME = 'blog';

var pool  = mysql.createPool({
    host     : '127.0.0.1',
    database:'blog',
    user     : 'root',
    password : 'abcd'
});

function Comment(comment){
 this.post_id=null;
    this.comments=comment.comments;
    this.commentor=comment.name;
    this.tiem=null;
};
module.exports = Comment;

Comment.prototype.getCommentsByPost=function getCommentsByPost(post,callback){

    var post_id=null;
    pool.getConnection(function(err,connection){

        var post_id_Sql="select id from posts where name=? and title=? and time=?";
        var post_id=null;
        connection.query(post_id_Sql,[post.name,post.title,post.time],function(err,result){
            if(err){
                console.log('post_id_Sql Error'+err.message);
                return;
            }
            post_id=result[0].id;
            var getCommentsByPost_Sql ="select * from comment where post_id=?";
            connection.query(getCommentsByPost_Sql,[post_id],function(err,result){
                    if(err){getCommentsByPost_Sql
                        console.log('getCommentsByPost_Sql Error '+ err.message);
                        return ;
                    }
                    callback(err,result);

                }
            );


        });

        connection.release();
    });

};

Comment.prototype.InsertComments=function InsertComments(post,comments,name,callback){

    pool.getConnection(function(err,connection){

        var post_id_Sql="select id from posts where name=? and title=? and time=?";
        var post_id=null;
        connection.query(post_id_Sql,[post.name,post.title,post.time],function(err,result){
            if(err){
                console.log('post_id_Sql Error'+err.message);
                return;
            }
            post_id=result[0].id;

            var time=new Date();
            var comment={
                time:time,
                comments:comments,
                commentor:name,
                post_id:post_id
            }
            var InsertComment_Sql ="insert into comment(post_id,comments,commentor,time) values(?,?,?,?)";
            connection.query(InsertComment_Sql,[comment.post_id,comment.comments,comment.commentor,comment.time],function(err,result){
                    if(err){
                        console.log('InsertComment_Sql Error '+ err.message);
                        return ;
                    }
                    callback(err,result);

                }
            );
        });

        connection.release();
    });

};